package com.okilo.online.app.lib.analyse.util

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.configs.OkiloConfigs.addParams
import com.okilo.online.app.pet.OkiloLibPet
import com.okilo.online.app.tools.log.OkiloLog
import org.json.JSONObject

object OkiloGoogleUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var _installReferrer: String = ""

    private var _installReferrerClient: InstallReferrerClient? = null

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) { referrer ->
            saveS2sInfo()
        }
    }

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        try {
            // 如果已经有referrer，直接回调
            if (_installReferrer.isNotBlank()) {
                success.invoke(_installReferrer)
                return
            }
            _installReferrerClient = InstallReferrerClient.newBuilder(context).build()
            _installReferrerClient?.startConnection(object : InstallReferrerStateListener {
                override fun onInstallReferrerSetupFinished(responseCode: Int) {
                    handleInstallReferrerResponse(responseCode, success)
                }
                override fun onInstallReferrerServiceDisconnected() {
                    OkiloLog.i("InstallReferrer service disconnected")
                }
            })
        } catch (e: Exception) {
            OkiloLog.e("Init InstallReferrer failed: $e")
            // 即使失败也回调，返回空字符串
            success.invoke(getInstallReferrer())
        }
    }

    /**
     * 处理InstallReferrer响应
     */
    private fun handleInstallReferrerResponse(responseCode: Int, success: (String) -> Unit) {
        when (responseCode) {
            InstallReferrerClient.InstallReferrerResponse.OK -> {
                handleSuccessResponse(success)
            }
            InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                OkiloLog.i( "FEATURE_NOT_SUPPORTED")
                cleanupClient()
                success.invoke("")
            }
            InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                OkiloLog.i("SERVICE_UNAVAILABLE")
                cleanupClient()
                success.invoke("")
            }
            else -> {
                OkiloLog.i("Unknown response code: $responseCode")
                cleanupClient()
                success.invoke("")
            }
        }
    }

    /**
     * 处理成功响应
     */
    private fun handleSuccessResponse(success: (String) -> Unit) {
        try {
            _installReferrer = _installReferrerClient?.installReferrer?.installReferrer ?: ""
            cleanupClient()
            success.invoke(_installReferrer)
        } catch (e: Exception) {
            OkiloLog.e("Get install referrer failed: $e")
            cleanupClient()
            success.invoke("")
        }
    }

    /**
     * 清理InstallReferrerClient
     */
    private fun cleanupClient() {
        try {
            _installReferrerClient?.endConnection()
        } catch (e: Exception) {
            OkiloLog.e("End connection failed: $e")
        } finally {
            _installReferrerClient = null
        }
    }


    /**
     * 获取Install Referrer
     * gclid123
     */
    fun getInstallReferrer(): String {
        return _installReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo() {
        if (OkiloConfigs.gOkiloLoginToken().isEmpty()) return
        val googleParams = JSONObject().addParams().apply {
            put("channelCode",getInstallReferrer())
            put("subChannelCode",getInstallReferrer())
            put("sourceType","google")
            put("path",OkiloConfigs.gOkiloRequestPath("GOOGLE_INSTALL"))
        }
        OkiloLibPet.submitOkiloLibDataRequest(googleParams)
    }
}